/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.transaction.jdbc;

import cn.easyplatform.dao.utils.DaoUtils;
import cn.easyplatform.transaction.ConnectionInfo;
import cn.easyplatform.transaction.Transaction;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class JdbcTransaction extends Transaction {

	private static AtomicLong TransIdMaker = new AtomicLong();

	private List<ConnectionInfo> list;

	private long id;

	public JdbcTransaction() {
		list = new ArrayList<ConnectionInfo>();
		id = TransIdMaker.getAndIncrement();
	}

	public void commit() throws SQLException {
		for (ConnectionInfo cInfo : list) {
			// 提交事务
			cInfo.getConn().commit();
			// 恢复旧的事务级别
			if (cInfo.getConn().getTransactionIsolation() != cInfo
					.getOldLevel())
				cInfo.getConn().setTransactionIsolation(cInfo.getOldLevel());
		}
	}

	@Override
	public Connection getConnection(DataSource dataSource) throws SQLException {
		for (ConnectionInfo p : list)
			if (p.getDs() == dataSource)
				return p.getConn();
		Connection conn = dataSource.getConnection();
		if (conn.getAutoCommit())
			conn.setAutoCommit(false);
		list.add(new ConnectionInfo(dataSource, conn, getLevel()));
		return conn;
	}

	public long getId() {
		return id;
	}

	@Override
	public void close() {
		for (ConnectionInfo cInfo : list) {
			try {
				// 试图恢复旧的事务级别
				if (!cInfo.getConn().isClosed()) {
					if (cInfo.getConn().getTransactionIsolation() != cInfo
							.getOldLevel())
						cInfo.getConn().setTransactionIsolation(
								cInfo.getOldLevel());
				}
			} catch (Throwable e) {
			} finally {
				DaoUtils.closeQuietly(cInfo.getConn());
			}
		}
		// 清除数据源记录
		list.clear();
	}

	@Override
	public void rollback() {
		for (ConnectionInfo cInfo : list) {
			try {
				cInfo.getConn().rollback();
			} catch (Throwable e) {
			}
		}
	}

}
